package com.sws.weixin.service.impl;


import com.alibaba.fastjson2.JSONObject;
import com.sws.common.core.domain.AjaxResult;
import com.sws.weixin.entity.TUser;
import com.sws.weixin.entity.TemplateSendDTO;
import com.sws.weixin.mapper.TUser2Mapper;
import com.sws.weixin.service.WxTemplateService;
import com.sws.weixin.token.TokenUtil;
import com.sws.weixin.util.HttpUtil;
import com.sws.wxtemplate.domain.WechatTemplate;
import com.sws.wxtemplate.mapper.WechatTemplateMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
public class WxTemplateServiceImpl implements WxTemplateService {

    @Autowired
    private TUser2Mapper tUserMapper;

    @Autowired
    private WechatTemplateMapper templateMapper;

    @Autowired
    private TokenUtil tokenUtil;

    @Override
    public AjaxResult sendTemplate(TemplateSendDTO dto) {
        try {
            // 1. 校验用户是否存在
            TUser user = tUserMapper.selectByOpenid(dto.getTouser());
            if (user == null) {
                return AjaxResult.error("微信用户不存在");
            }

            // 2. 获取模板信息
            WechatTemplate template = templateMapper.selectByWxTemplateId(dto.getTemplateId());
            if (template == null) {
                return AjaxResult.error("模板不存在或已停用");
            }

            // 3. 构建消息数据（核心修改）
//            JSONObject data = buildTemplateData(template.getContent(), dto.getTemplateParams());

            // 3. 构建消息数据
            JSONObject requestData = new JSONObject();
            requestData.put("touser", dto.getTouser());
            requestData.put("template_id", dto.getTemplateId());

            // 构建data对象
            JSONObject data = new JSONObject();
            for (Map.Entry<String, Object> entry : dto.getData().entrySet()) {
                JSONObject item = new JSONObject();
                item.put("value", entry.getValue());
                data.put(entry.getKey(), item);
            }
            requestData.put("data", data);

            // 4. 调用微信接口
            String result = sendWechatMessage(requestData.toJSONString());
            JSONObject resultJson = JSONObject.parseObject(result);

            if (resultJson.getIntValue("errcode") == 0) {
                return AjaxResult.success("发送成功", resultJson.getString("msgid"));
            }
            return AjaxResult.error("发送失败: " + resultJson.getString("errmsg"));
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("系统异常: " + e.getMessage());
        }
    }


    private String sendWechatMessage(String requestBody) {
        String url = String.format(
                "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=%s",
                tokenUtil.getAccessToken()
        );
        return HttpUtil.doPost2(url, requestBody);
    }

}